package model

import (
	"fmt"
	"choujiang/common/db"
)

type GoodsCoupon struct {
	Id         int64  `xorm:"INT(11) not null pk autoincr" json:"id"`
	Code       string `xorm:"VARCHAR(20) not null" json:"code"`
	UserId     int64  `xorm:"INT(11) not null default 0" json:"user_id"`
	GoodsId    int64  `xorm:"INT(11) not null default 0" json:"goods_id"`
	Status     int64  `xorm:"INT(11) not null" json:"status"`
	ExchangeAt int64  `xorm:"INT(11) not null default 0" json:"exchange_at"`
	CreatedAt  int64  `xorm:"not null default 0 INT(11) created" json:"created_at"`
	UpdatedAt  int64  `xorm:"not null default 0 INT(11) updated" json:"updated_at"`
	Source     int64  `xorm:"INT(3) not null default 1" json:"source"`
}

func (u *GoodsCoupon) Insert() (*GoodsCoupon, error) {
	_, err := db.MysqlEngine.InsertOne(u)
	return u, err
}

func (u *GoodsCoupon) Update() (*GoodsCoupon, error) {
	_, err := db.MysqlEngine.ID(u.Id).Update(u)
	return u, err
}

func GetCouponByCode(code string) *GoodsCoupon {
	coupon := new(GoodsCoupon)
	has, err := db.MysqlEngine.Where("code=?", code).Get(coupon)
	fmt.Printf("GetCouponByCode err %+v\n", err)
	if !has || err != nil {
		return nil
	}
	return coupon
}
